package com.zerui.manager.app.openplan.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.openplan.OpenPlan;
import com.zerui.manager.openplan.OpenPlanDevice;
import com.zerui.manager.openplan.gateway.OpenPlanGateWay;
import com.zerui.manager.web.cmd.OpenPlanDeviceAddCmd;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wh
 * @title: OpenPlanAddCmdExe
 * @description:
 * @date 2023/5/05 9:42
 */
@Component
@CatchAndLog
public class OpenPlanDeviceAddCmdExe {

	@Resource
	private OpenPlanGateWay openPlanGateWay;

	public Response execute(OpenPlanDeviceAddCmd cmd) {
		OpenPlan openPlan = openPlanGateWay.selectById(cmd.getPlanId());
		if(ObjectUtils.isEmpty(openPlan)){
			throw new BizException("开门计划不存在");
		}
		Map<Long,Long> openPlanMap = openPlanGateWay.getOpenPlanDeviceMapById(cmd.getDeviceIds());
		List<OpenPlanDevice> openPlanDevices = new ArrayList<>();

		cmd.getDeviceIds().forEach(e->{
			if(!openPlanMap.containsKey(e)){
				openPlanDevices.add(OpenPlanDevice.builder()
						.deviceId(e)
						.openPlanId(cmd.getPlanId())
						.build());
			}
		});
		if(CollectionUtils.isNotEmpty(openPlanDevices)){
			openPlanGateWay.addBatchOpenPlanDevice(openPlanDevices);
		}
		return Response.buildSuccess();
	}
}
